package test;

import java.util.Observable;

/**
 * Created by Connor Madden.
 * User: Connor Madden
 * Date: 19/08/11
 * Time: 5:09 PM
 */
public class Lift extends Observable {
    public enum Change {
        LOC_CHANGE, DOOR_OPEN, DOOR_CLOSE
    }

    int loc;
    int prevLoc;
    boolean doorOpen;

    /**
     * The constructor specifying the location (<tt>loc</tt>)
     * and setting the previous location (<tt>prevLoc</tt>) to <tt>loc</tt>.
     *
     * @param loc the location
     */
    public Lift(int loc) {
        this.loc = loc;
        prevLoc = loc;
        doorOpen = false;
    }

    /**
     * Move to the location specified then notify observers
     *
     * @param loc the location
     */
    public void move(int loc) {
        setChanged();
        prevLoc = this.loc;
        this.loc = loc;
        notifyObservers(Change.LOC_CHANGE);
    }

    /**
     * Return the location
     *
     * @return the location
     */
    public int getLoc() {
        return loc;
    }

    /**
     * Set location
     *
     * @param loc the location
     */
    public void setLoc(int loc) {
        this.loc = loc;
        notifyObservers(Change.LOC_CHANGE);
    }

    /**
     * Return previous location
     *
     * @return previous location
     */
    public int getPrevLoc() {
        return prevLoc;
    }

    /**
     * Set door to open state
     *
     * @return <tt>true</tt> if door has changed state
     */
    public boolean openDoor() {
        if (doorOpen) return false;
        else {
            setChanged();
            doorOpen = true;
            notifyObservers(Change.DOOR_OPEN);
            return true;
        }
    }

    /**
     * Set door to closed state
     *
     * @return <tt>true</tt> if door has changed state
     */
    public boolean closeDoor() {
        if (!doorOpen) return false;
        else {
            setChanged();
            doorOpen = false;
            notifyObservers(Change.DOOR_CLOSE);
            return true;
        }
    }

    /**
     * return <tt>true</tt> if door is open
     *
     * @return <tt>true</tt> if door is open
     */
    public boolean isDoorOpen() {
        return doorOpen;
    }

    /**
     * Return the last direction of travel, <tt>1</tt> for positive move, <tt>-1</tt> for negative move
     * and <tt>0</tt> for no move
     *
     * @return <tt>1</tt> for positive move, <tt>-1</tt> for negative move and <tt>0</tt> for no move
     */
    public int getLastDir() {
        int x = loc - prevLoc;
        if (x == 0) return 0;
        else
            return x / Math.abs(x);
    }
}
